All files / util node_api.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 3/3
100% Lines 6/6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                                                                                  1x     2x   2x 2x 1x   1x                            
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { AnyJs } from './misc';
 
/*
 * Utilities for dealing with node.js-style APIs. See nodePromise for more
 * details.
 */
 
/**
 * Creates a node-style callback that resolves or rejects a new Promise. The
 * callback is passed to the given action which can then use the callback as
 * a parameter to a node-style function.
 *
 * The intent is to directly bridge a node-style function (which takes a
 * callback) into a Promise without manually converting between the node-style
 * callback and the promise at each call.
 *
 * In effect it allows you to convert:
 *
 * @example
 * new Promise((resolve: (value?: fs.Stats) => void,
 *              reject: (error?: any) => void) => {
 *   fs.stat(path, (error?: any, stat?: fs.Stats) => {
 *     if (error) {
 *       reject(error);
 *     } else {
 *       resolve(stat);
 *     }
 *   });
 * });
 *
 * Into
 * @example
 * nodePromise((callback: NodeCallback<fs.Stats>) => {
 *   fs.stat(path, callback);
 * });
 *
 * @param action a function that takes a node-style callback as an argument and
 *     then uses that callback to invoke some node-style API.
 * @return a new Promise which will be rejected if the callback is given the
 *     first Error parameter or will resolve to the value given otherwise.
 */
export function nodePromise<R>(
  action: (callback: NodeCallback<R>) => void
): Promise<R> {
  return new Promise(
    (resolve: (value?: R) => void, reject: (error?: AnyJs) => void) => {
      action((error?: AnyJs, value?: R) => {
        if (error) {
          reject(error);
        } else {
          resolve(value);
        }
      });
    }
  );
}
 
/**
 * A node-style callback which passes an Error as the first argument if there
 * was an error, or passes null and a proper value
 */
export interface NodeCallback<R> {
  (error?: AnyJs, value?: R): void;
}